import cv2 as cv
import os
import sys
from PyCmpltrtok.common import IMG_FORMATS


class DownSampleException(Exception):
    pass


def down_sample(img, xn):
    H, W = img.shape[:2]
    if H / xn - float(H // xn) or W / xn - float(W // xn):
        raise DownSampleException(f'Cannot down sample x{xn} perfectly!')

    dst = cv.resize(img, [W // xn, H // xn], interpolation=cv.INTER_CUBIC)
    return dst


def down_smaple_dir(src_dir, dst_dir, xn):
    xnames = os.listdir(src_dir)
    for xname in xnames:
        ext = os.path.splitext(xname)[1]
        if ext and ext[1:] not in IMG_FORMATS:
            print(f'{xname} is not a image file.')
            continue
        dst_path = os.path.join(dst_dir, xname)
        if os.path.exists(dst_path):
            print(f'Warning: {dst_path} existed!', file=sys.stderr)
            continue
        src_path = os.path.join(src_dir, xname)
        img = cv.imread(src_path, cv.IMREAD_UNCHANGED)
        dst = down_sample(img, xn)
        cv.imwrite(dst_path, dst)
        print(f'Written: {dst_path}')


if '__main__' == __name__:
    src_dir = 'C:\_data\_job_root\workspace\colmap\my-pc-2-monitors\images'
    dst_dir = 'C:\_data\_job_root\workspace\colmap\my-pc-2-monitors-x8\images'
    xn = 8
    down_smaple_dir(src_dir, dst_dir, xn)
